const player = {
  DOM: document.querySelector('.player'),
  state: 0, //0站立 1移动
  moveSpeed: 1.8,
  moveDir: 'right',
  isJump: false,
  jumpFlag: 1, // 1 上升 2 下降
  jumpHeight: 60,
  jumpSpeed: 5,
  currentBottom: 0,
  pipeInfo: {
    active: false,
    x1: 0,
    x2: 0
  },
  isInv: false,
  BigFlag: 'small',  // 是否是变大的
  width: 0,
  height: 0,
  x1: 0,
  x2: 0,
  y1: 0,
  y2: 0,
  bgIndex: 2,
  hp: 1,
  updateXY: function () {
    this.width = this.DOM.offsetWidth
    this.height = this.DOM.offsetHeight
    this.x1 = this.DOM.style.left.substr(0, this.DOM.style.left.length - 2) - 0;
    this.x2 = this.x1 + this.width
    this.y1 = this.DOM.style.bottom.substr(0, this.DOM.style.bottom.length - 2) - 0
    this.y2 = this.y1 + this.height
  }
}

var queryBox = document.querySelector('.queryBox')
queryBox.b = 70
var queryItems = document.querySelectorAll('.queryBox .item')
var query = document.querySelector('.query')
player.updateXY()
var storeBox = document.querySelector('.storeBox span')
var buff;
var pipes = document.querySelectorAll('.pipe')

function keyDown (e) {
  if (e.key == 'a') {
    player.moveDir = 'left'
    player.state = 1
  }

  if (e.key == 'd') {
    player.moveDir = 'right'
    player.state = 1

  }
  if (e.key == 'j' && player.isJump == false) {

    player.isJump = true
    player.jumpFlag = 1

  }
}
function startGame () {

  document.addEventListener('keydown', keyDown)
  document.addEventListener('keyup', function (e) {
    if (e.key == 'a') {
      player.state = 0
    }

    if (e.key == 'd') {
      player.state = 0

    }

  })
}
document.querySelector('.start').onclick = function () {
  this.parentNode.style.display = 'none'
  document.querySelector('.box').style.display = 'block'
  startGame()
}
// 加分
function addStore () {
  var div = document.createElement('div')
  div.innerHTML = '+100'
  div.classList.add('store')
  player.DOM.appendChild(div)
  setTimeout(() => {
    player.DOM.removeChild(div)
  }, 800);
  storeBox.innerHTML = storeBox.innerHTML - 0 + 100

  if (buff) {
    buff.style.width = buff.offsetWidth + 4 + 'px'
    buff.style.height = buff.style.width
    // 判断buff是否达到最大值
    if (buff.offsetWidth >= 52) {
      var buffTimer = setInterval(() => {
        // buff下落时 如果碰到玩家
        if (player.x2 > queryBox.offsetLeft && player.x1 < queryBox.offsetLeft + queryBox.offsetWidth) {
          if (queryBox.b <= 0) {
            clearInterval(buffTimer)
            queryBox.removeChild(buff)
            player.BigFlag = 'big'
            player.DOM.classList.add('big')
            player.jumpHeight = 80
            player.jumpSpeed = 6
          } else if (queryBox.b <= 30) {
            playerDie()
          }
        }
        // 落地后墙体消失
        if (queryBox.b <= 0) {
          if (!query) return
          queryBox.removeChild(query)
          query = null
          buff.style.bottom = '0px'
        } else {
          queryBox.b -= 4
          queryBox.style.bottom = queryBox.b + 'px'
        }

      }, 40);
    }
  }
}

// 玩家死亡
function playerDie () {
  player.hp = 0
  player.DOM.style.background = 'url(images/die.png)'
  player.DOM.style.animation = 'gameOver 2s forwards'

}
// 创建敌人
function createEnemy (node) {
  var dom = document.createElement('div')
  dom.classList.add('en1')
  var parentLeft = node.offsetLeft
  dom.style.left = parentLeft + 'px'
  node.appendChild(dom)
  console.log(node.offsetLeft);
  dom.classList.add('active')

  setTimeout(function () {
    var dir = 'right';
    var enemy = setInterval(() => {
      // 更改移动方向
      var worldX = dom.offsetLeft + queryBox.offsetLeft
      if (worldX + 24 >= 280) {
        dir = 'left'
      }

      dir == 'right' ? dom.style.left = dom.offsetLeft - 0 + 2 + 'px' : dom.style.left = dom.offsetLeft - 0 - 2 + 'px'
      if (dom.offsetLeft >= 70 && dom.offsetTop < 70) {
        dom.style.top = dom.offsetTop + 8 + 'px'
      }
      // 超出屏幕的敌人自动销毁
      if (dom.offsetLeft < -90) {
        clearInterval(enemy)
        node.removeChild(dom)
      }

      if (dom.offsetTop < 70) return

      if (player.x2 >= worldX + 10 && player.x1 <= worldX + 24 && player.y1 < 17) {
        if (player.jumpFlag == 2) {
          dom.classList.remove('active')
          dom.classList.add('die')
          addStore()
          setTimeout(() => {
            node.removeChild(dom)
          }, 500);
        } else {
          playerDie()

        }
        clearInterval(enemy)
      }


    }, 40);
  }, 400)
}
// 创建金币
function createMoney (money, node) {

  node.setAttribute('data-money', money - 1)
  var dom = document.createElement('div')
  dom.classList.add('money')
  dom.style.left = node.offsetLeft + 'px'
  node.appendChild(dom)
  dom.classList.add('money-active')
  // 加分
  addStore()
  setTimeout(() => {
    node.removeChild(dom)
  }, 500);
}
//创建buff
function createBuff () {
  buff = document.createElement('div')
  buff.classList.add('buff')
  buff.classList.add('buff-active')
  queryBox.appendChild(buff)
}
// 碰撞检测
function checkCollisions () {
  // 获取障碍物坐标
  var queryLeft = queryBox.offsetLeft;

  [...queryItems].forEach(item => {
    var itemLeft = queryLeft + item.offsetLeft
    var itemRight = itemLeft + 24

    if (player.x2 > (itemLeft + 12) && player.x1 < (itemRight - 12)) {

      // 判断碰撞的是怪物盒子还是buff盒子
      if (item.className.indexOf('enemy') !== -1) {
        // 创建怪物
        var money = item.getAttribute('data-money')
        money > 0 ? createMoney(money, item) : createEnemy(item)
      } else {
        // 创建BUFF
        console.log(buff);
        if (buff) {
          return
        } else {
          createBuff(item)
        }
      }
      // 播放碰撞动画
      item.style.animation = 'coolAni 0.3s linear'
      setTimeout(() => {
        item.style.animation = ''
      }, 300);
    }
  })
}

const update = setInterval(() => {
  if (player.hp == 0) return
  //更新站立状态方向
  if (player.state == 0) {
    player.DOM.style.background = `url(images/stand_${player.BigFlag}_${player.moveDir}.png)`
  }

  if (player.state == 1) {
    var moveErr = false
    // 切换背景图 完成移动动画
    if (player.isJump == false) {
      player.bgIndex == 7 && (player.bgIndex = 2)
      var index = player.bgIndex * 0.5 + ''

      if (index.length == 1) {
        player.DOM.style.background = `url(images/move_${player.BigFlag}_${player.moveDir}_${index}.png)`
      }
      player.bgIndex++
    }

    var move = player.moveDir == 'left' ? player.x1 - player.moveSpeed : player.x1 + player.moveSpeed

    if (player.pipeInfo.active && (player.x2 < player.pipeInfo.x1 + 5 || player.x1 > player.pipeInfo.x2 - 5)) {

      // 超出所在管道范围
      var toBottom0 = setInterval(function () {
        player.updateXY();
        if (player.y1 <= 0) {
          // 
          console.log(999);
          player.DOM.style.bottom = '0px'
          player.pipeInfo.active = false
          player.currentBottom = 0
          player.jumpFlag = 1
          clearInterval(toBottom0)
          return
        }
        player.DOM.style.bottom = player.y1 - 5 + 'px'
        player.jumpFlag = 2
      }, 40)
    }
    for (var v of [...pipes]) {
      if (player.y1 > v.offsetHeight - 2 || player.x1 > 800) {
        continue
      }

      if (player.x2 >= v.offsetLeft && player.x2 < v.offsetLeft + v.offsetWidth) {
        player.DOM.style.left = move - 2 + 'px'
        console.log(99);
        moveErr = true
        break

      } else if (player.x1 <= v.offsetLeft + v.offsetWidth && player.x1 > v.offsetLeft) {

        player.DOM.style.left = move + 2 + 'px'
        moveErr = true
        break

      }
    }

    if (player.x1 >= 735 && player.x1 <= 800) {

      moveErr = true
      player.DOM.style.left = 734 + 'px'
    }

    if (moveErr == false) {

      player.DOM.style.left = move + 'px'

    }
    player.updateXY();
  }

  // 跳跃状态
  if (player.isJump) {
    // 

    player.DOM.style.background = `url(images/jump_${player.BigFlag}_${player.moveDir}.png)`
    player.updateXY()
    // 判断是否着地
    if (player.y1 <= player.currentBottom && player.jumpFlag == 2) {
      player.isJump = false
      player.jumpFlag = 1
      player.DOM.style.bottom = player.currentBottom + 'px'
      return
    }
    // 是否到达最大高度
    if (player.y1 >= player.jumpHeight + player.currentBottom) {
      player.jumpFlag = 2
      checkCollisions()
      for (var v of [...pipes]) {
        if (player.y1 < v.offsetHeight) {
          break
        }
        if (player.x2 >= v.offsetLeft && player.x2 < v.offsetLeft + v.offsetWidth || player.x1 <= v.offsetLeft + v.offsetWidth && player.x1 > v.offsetLeft) {
          player.currentBottom = v.offsetHeight
          // 修改管道信息
          player.pipeInfo.active = true
          player.pipeInfo.x1 = v.offsetLeft
          player.pipeInfo.x2 = v.offsetLeft + v.offsetWidth
        }
      }
    }

    // 更新跳跃
    player.DOM.style.bottom = (player.jumpFlag == 1 ? player.y1 + player.jumpSpeed : player.y1 - player.jumpSpeed) + 'px';

  }


}, 30);
var enemy2 = document.querySelectorAll('.enemy2')
var enemyBox = document.querySelector('.enemyBox')
for (var item of enemy2) {
  item.bgIndex = 2
  item.dire = 'right'
  item.hp = 2
}
const enemy2Manager = setInterval(() => {
  var enemy3 = document.querySelector('.enemy3')
  if (enemy3) {
    var en3X = enemy3.style.left.replace('px', '') - 0
    var en3Left = en3X + enemyBox.offsetLeft
    var en3Right = en3Left + enemy3.offsetWidth
    if (player.y1 <= 20 && player.x2 > en3Left && player.x2 < en3Right + player.width) {
      playerDie()
      return
    }
    if (en3X <= 0) {
      enemyBox.removeChild(enemy3)
    }
    enemy3.style.left = en3X - 20 + 'px'
  }
  for (var item of enemy2) {
    var itemX = item.style.left.replace('px', '') - 0
    var itemLeft = itemX + enemyBox.offsetLeft
    var itemRight = itemLeft + item.offsetWidth
    if (player.y1 <= 20 && player.x2 > itemLeft && player.x2 < itemRight + player.width) {
      if (player.jumpFlag == 2) {
        item.hp--
        if (item.hp == 0) {
          setTimeout(() => {
            item.hp--
          }, 200);
        }
        if (player.x1 < itemLeft) {
          item.dire = 'right'
        } else {
          item.dire = 'left'
        }
      } else if (player.isJump == false && item.hp != 1 && item.hp != 0) {
        playerDie()
      }
    }
    if (itemX >= 240) {
      item.dire = 'left'
      item.style.backgroundImage = `url(images/enemy_${item.dire}_2_1.png)`

    }
    if (itemX <= 2) {
      item.dire = 'right'
      item.style.backgroundImage = `url(images/enemy_${item.dire}_2_1.png)`
    }
    if (item.hp == 1) {
      item.style.backgroundImage = `url(images/enemy2_die.png)`
      item.style.height = '18px'
      continue
    }
    if (item.hp <= 0) {
      item.style.backgroundImage = `url(images/enemy2_die.png)`

      item.style.left = item.dire == 'left' ? itemX - 10 + 'px' : itemX + 10 + 'px'
      continue
    }
    // 切换背景图 完成移动动画
    item.bgIndex == 5 && (item.bgIndex = 2)
    var index = item.bgIndex * 0.5 + ''

    if (index.length == 1) {
      item.style.backgroundImage = `url(images/enemy_${item.dire}_2_${index}.png)`
    }
    item.bgIndex += 0.5


    item.style.left = item.dire == 'left' ? itemX - 3 + 'px' : itemX + 3 + 'px'

  }
}, 80);
const flower = document.querySelector('.flower')
flower.flag = 1 // 0待机 1上升 2下降
flower.timer = null
const enemy3Manager = setInterval(() => {
  var div = document.createElement('div')
  div.classList.add('enemy3')
  div.style.left = '270px'
  enemyBox.appendChild(div)
}, 2000);

const flowerManager = setInterval(() => {
  if (flower.flag == 0) return


  if (flower.offsetTop <= 0) {
    flower.flag = 2
  }
  if (flower.offsetTop >= 24 && flower.flag == 2) {
    flower.flag = 0
    flower.timer = setTimeout(function () {
      flower.flag = 1
    }, 1500)
  }
  flower.style.top = flower.flag == 1 ? flower.offsetTop - 2 + 'px' : flower.offsetTop + 2 + 'px'
  if (player.x1 > 800) return

  if (player.y1 <= 60 && player.x2 > flower.offsetLeft + 705 && player.x2 < flower.offsetLeft + 705 + 16 + player.width) {
    player.x1 = 980
    document.removeEventListener('keydown', keyDown)
    player.state = 0
    player.DOM.style.animation = ' fly 1.5s  linear forwards'
    player.DOM.onanimationend = function () {
      alert('胜利')

    }
  }
}, 60);